<template>
  <div :id="id">
    <Portal to="right-disable"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  :style="{height: (gadgetHeight + heightoffset -20) + 'px'}">
        <el-card :style="{height: (gadgetHeight + heightoffset -20) + 'px'}"
                 shadow="never"
                 class="aui-card--fill">
          <div>
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(gadgetSetting.headerTitle && gadgetSetting.headerTitle.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <MoreMenu :slicer='slicer'
                        :gadgetId='id'
                        :gadgetType='gadgetInfo.com'
                        @updateQuery="query"
                        @fullScreen="fullScreen" />
            </div>
            <div class="control-section"
                 style="padding: 5px 10px;">
              <div class="content-wrapper"
                   v-loading="loading">
                <ejs-pivotview v-show="isHasData"
                               :dataSourceSettings="pivotTableDefaultSetting.dataSourceSettings"
                               :gridSettings="pivotTableDefaultSetting.gridSettings"
                               :width="pivotTableDefaultSetting.width"
                               :style="{height: gadgetHeight + 'px'}"
                               :height="gadgetHeight"
                               :allowDrillThrough="pivotTableDefaultSetting.allowDrillThrough"
                               :showTooltip="pivotTableDefaultSetting.showTooltip"
                               :showFieldList="pivotTableDefaultSetting.showFieldList"
                               :load="load"
                               :allowExcelExport="pivotTableDefaultSetting.allowExcelExport"
                               :allowConditionalFormatting="pivotTableDefaultSetting.allowConditionalFormatting"
                               :allowNumberFormatting="pivotTableDefaultSetting.allowNumberFormatting"
                               :allowPdfExport="pivotTableDefaultSetting.allowPdfExport"
                               :showToolbar="pivotTableDefaultSetting.showToolbar"
                               :allowCalculatedField="pivotTableDefaultSetting.allowCalculatedField"
                               :toolbar="pivotTableDefaultSetting.toolbar"
                               :saveReport="saveReport"
                               :fetchReport="fetchReport"
                               :toolbarRender="beforeToolbarRender"
                               :displayOption="pivotTableDefaultSetting.displayOption"
                               :chartSettings="pivotTableDefaultSetting.chartSettings"
                               :enableValueSorting="pivotTableDefaultSetting.enableValueSorting"
                               @beginDrillThrough="beginDrillThrough"
                               :showGroupingBar='true'
                               ref="pivotview">
                </ejs-pivotview>
                <div v-if="!isHasData"
                     class="gadget-no-data">
                  <el-image @click="query()"
                            :src='noDataImageUrl'
                            fit='fill'></el-image>
                </div>
              </div>
            </div>
          </div>
          <!--<div v-if='showHeader'
             slot="header"
             class="clearfix">
          <span>{{ headText }}</span>
        </div>-->
        </el-card>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
  </div>
</template>

<script>

// import model from '@/components/gadget/query-model/query-model.vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import mixinViewModule from '@/mixins/report-view-module'

import ticketLinkFormat from './template/TicketLinkFormat'
import timeEntryLinkFormat from './template/TimeEntryLinkFormat'

export default {
  mixins: [mixinGadgetViewModule, mixinViewModule],
  components: { model: () => import('@/components/gadget/query-model/query-model') },
  watch: {
    editMode (val) {
      if (!val) {
        this.pivotTableDefaultSetting.toolbar = ['Grid', 'Chart', 'Export', 'SubTotal', 'GrandTotal', 'Formatting', 'FieldList']
        this.saveGadgetSetting()
      } else {
        this.pivotTableDefaultSetting.toolbar = ['Save', 'Load', 'Grid', 'Chart', 'Export', 'SubTotal', 'GrandTotal', 'Formatting', 'FieldList']
      }
    },
    immediate: true
  },
  data () {
    return {
      gadgetSetting: {},
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      heightoffset: 60,
      cardheight: 0,
      showHeader: false,
      headText: '',
      pivotTableDefaultSetting: {
        dataSourceSettings: {
          dataSource: this.dataList,
          values: [],
          formatSettings: [],
          columns: [],
          rows: [],
          filters: [],
          calculatedFieldSettings: []
        }
      },
      dataForm: {
        searchDate: null
      },
      dataList: [],
      defaultDrillThroughSetting: null,
      TicketLinkFormat: function () {
        return { template: ticketLinkFormat }
      },
      TimeEntryLinkFormat: function () {
        return { template: timeEntryLinkFormat }
      },
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          gadgetSetting: {
            headerTitle: '',
            headerDescription: ''
          }
        }
      }
    }
  },

  created () {
    this.subscribeMessage('runReport', this.query)
    if (this.editMode) {
      this.pivotTableDefaultSetting.toolbar = ['Save', 'Load', 'Grid', 'Chart', 'Export', 'SubTotal', 'GrandTotal', 'Formatting', 'FieldList']
    }
    this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
    this.$store.state.isWidget = false
  },
  mounted () {

  },
  methods: {
    load (item) {
      this.grid = this.$refs.pivotview // item
      this.gadgetHeight = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100 :(this.gadgetInfo.h * 20) - this.heightoffset
      this.cardheight = (this.gadgetHeight + this.heightoffset - 20) + 'px'
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = (newH * 20) - this.heightoffset
      this.cardheight = (this.gadgetHeight + this.heightoffset - 20) + 'px'
      this.gadgetWidth = newWPx
    },
    query () {
      this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      this.isHasData = false
      this.loading = true
      var _self = this
      var param = {
        ...this.slicer,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr()
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        _self.verifyHasData(res)
        let pivotObj = _self.$refs.pivotview.ej2Instances
        // process data
        if (res.data) {
          _self.dataList = res.data
        }
        // process config &  refresh UI
        if (res.config && res.config.report) {
          res.config.report.dataSourceSettings.dataSource = res.data
          pivotObj.dataSourceSettings = res.config.report.dataSourceSettings
          this.defaultDrillThroughSetting = res.config.report
          // pivotObj.pivotRefresh()
          _self.showHeader = res.config.showHeader || false
          _self.headText = res.config.headText || ''
          _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
        } else {
          pivotObj.dataSourceSettings.dataSource = _self.dataList
        }
        if (_self.showHeader) {
          this.heightoffset = 100
        } else {
          this.heightoffset = 60
        }
        _self.gadgetHeight = _self.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100 :(_self.gadgetInfo.h * 20) - _self.heightoffset
        _self.cardheight = (_self.gadgetHeight + _self.heightoffset - 20) + 'px'

        _self.isHasData = true
        pivotObj.pivotRefresh()
        this.loading = false
      }).catch(() => {
        this.loading = false
      }).finally(() => {
        this.loading = false
        this.updateGadgetLoadingStatus(!this.loading)
      })
    },
    saveGadgetSetting () {
      var _self = this
      var pvtable = JSON.parse(_self.reportSetting)
      pvtable.dataSourceSettings.dataSource = null
      pvtable.pivotValues = null
      const params = {
        gadgetSetting: {
          report: pvtable,
          showHeader: _self.showHeader || false,
          headText: _self.headText || ''
        },
        gadgetId: this.id
      }
      // putReportsSettingApi
      this.$interface.reports.putReportsSettingApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return _self.$message.error(res.msg)
        }
      })
    },
    beginDrillThrough (e) {
      // drillThroughSetting:[
      //   {  field:'Time Entry Id',
      //   fieldTemplateName:'TimeEntryLinkFormat'
      //   }
      // ]
      if (this.defaultDrillThroughSetting.drillThroughSetting) {
        const drillThroughSetting = this.defaultDrillThroughSetting.drillThroughSetting
        if (e.gridObj && e.gridObj.columns.length > 0) {
          // process link column
          for (let index = 0; index < e.gridObj.columns.length; index++) {
            const columnfield = e.gridObj.columns[index].field
            for (let i = 0; i < drillThroughSetting.length; i++) {
              const drillThroughTemplate = drillThroughSetting[i]
              if (drillThroughTemplate.field === columnfield && drillThroughTemplate.fieldTemplateName === 'TimeEntryLinkFormat') {
                e.gridObj.columns[index].template = this.TimeEntryLinkFormat
              } else if (drillThroughTemplate.field === columnfield && drillThroughTemplate.fieldTemplateName === 'TicketLinkFormat') {
                e.gridObj.columns[index].template = this.TicketLinkFormat
              }
            }
          }
        }
      }
    }
  }
}
</script>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardHeader > span {
  display: inline-block;
  width: calc(100% - 30px);
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.e-custom-class {
  text-decoration: underline;
}
.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}
</style>
